/**
 * 全站路由配置
 *
 * 建议:
 * 1. 代码中路由统一使用name属性跳转(不使用path属性)
 */
import Vue from 'vue'
import Router from 'vue-router'
import http from '@/utils/httpRequest'
import {isURL} from '@/utils/validate'
import {clearLoginInfo} from '@/utils'

Vue.use(Router)

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
const _import = require('./import-' + process.env.NODE_ENV)

// 全局路由(无需嵌套上左右整体布局)
const globalRoutes = [
	{path: '/404', component: _import('common/404'), name: '404', meta: {title: '404未找到'}},
	{path: '/login', component: _import('common/login'), name: 'login', meta: {title: '登录'}}
]

// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = {
	path: '/',
	component: _import('main'),
	name: 'main',
	redirect: {name: 'home'},
	meta: {title: '主入口整体布局'},
	children: [
		// 通过meta对象设置路由展示方式
		// 1. isTab: 是否通过tab展示内容, true: 是, false: 否
		// 2. iframeUrl: 是否通过iframe嵌套展示内容, '以http[s]://开头': 是, '': 否
		// 提示: 如需要通过iframe嵌套展示内容, 但不通过tab打开, 请自行创建组件使用iframe处理!
		{path: '/home', component: _import('common/home'), name: 'home', meta: {title: '数据中心'}},
		{path: '/userList', component: _import('user/userList'), name: 'userList', meta: {title: '用户中心', isTab: true}},
		{path: '/allocationList',component: _import('allocation/allocationList'),name: 'allocationList',meta: {title: '配置列表', isTab: true}},
		{path: '/financeList', component: _import('finance/financeList'), name: 'financeList', meta: {title: '财务中心', isTab: true}},
		{path: '/message', component: _import('message/message'), name: 'message', meta: {title: '消息中心', isTab: true}},
		{path: '/taskConfig', component: _import('taskConfig/taskConfig'), name: 'taskConfig', meta: {title: '服务配置', isTab: true}},
		{path: '/bannerList', component: _import('banner/bannerList'), name: 'bannerList', meta: {title: '首页装修', isTab: true}},
		{path: '/shopsList', component: _import('shopsList/shopsList'), name: 'shopsList', meta: {title: '商户管理', isTab: true}},
		{path: '/shopAutonym', component: _import('shopAutonym/shopAutonym'), name: 'shopAutonym', meta: { title: '商户审核',isTab: true} },
		{path: '/shopsOrder', component: _import('shopsList/shopsOrder'), name: 'shopsOrder', meta: {title: '商户订单列表', isTab: false}},
		{path: '/shopDatas', component: _import('shopsList/shopDatas'), name: 'shopDatas', meta: {title: '商户收入统计', isTab: false}},
		{path: '/bondList', component: _import('shopsList/bondList'), name: 'bondList', meta: {title: '保证金明细', isTab: false}},
		{path: '/pingjiaList', component: _import('shopsList/pingjiaList'), name: 'pingjiaList', meta: {title: '评价明细', isTab: false}},
		{path: '/shopWallet', component: _import('shopsList/shopWallet'), name: 'shopWallet', meta: {title: '商户钱包', isTab: false}},
		{path: '/mission', component: _import('mission/mission'), name: 'mission', meta: {title: '服务列表', isTab: true}},
		{path: '/diagnosis', component: _import('diagnosis/diagnosis'), name: 'diagnosis', meta: {title: '陪诊师管理', isTab: true}},
		{path: '/system', component: _import('mission/system'), name: 'system', meta: {title: '系统服务', isTab: true}},
		{path: '/missionsye', component: _import('sysmission/missionsye'), name: 'missionsye', meta: {title: '活动派送', isTab: true}},
		{path: '/materialsList', component: _import('materials/materialsList'), name: 'materialsList', meta: {title: '帮助中心', isTab: true}},
		{path: '/missionAdd', component: _import('mission/missionAdd'), name: 'missionAdd', meta: {title: '发布服务', isTab: false}},
		{path: '/missionRedact',component: _import('sysmission/missionRedact'),name: 'missionRedact',meta: {title: '修改服务', isTab: false}},
		{path: '/userDetail', component: _import('user/userDetail'), name: 'userDetail', meta: {title: '用户详情', isTab: false}},
		{path: '/userDetail1', component: _import('user/userDetail1'), name: 'userDetail1', meta: {title: '用户详情', isTab: false}},
		{path: '/missionDetails',component: _import('mission/missionDetails'),name: 'missionDetails',meta: {title: '服务详情', isTab: false}},
		{path: '/fitmentList', component: _import('fitment/fitmentList'), name: 'fitmentList', meta: {title: '首页装修', isTab: false}},
		{path: '/integral', component: _import('integral/integral'), name: 'integral', meta: {title: '积分推送', isTab: true}},
		{path: '/integralDetail',component: _import('integral/integralDetail'),name: 'integralDetail',meta: {title: '活动详情', isTab: false}},
		{path: '/campus', component: _import('campus/campus'), name: 'campus', meta: {title: '片区列表', isTab: true}},
		{path: '/missionComplain',component: _import('mission/missionComplain'),name: 'missionComplain',meta: {title: '服务投诉', isTab: true}},
		{path: '/autonym', component: _import('autonym/autonym'), name: 'autonym', meta: {title: '实名认证', isTab: true}},

		{path: '/materialLink', component: _import('locality/materialLink'), name: 'materialLink', meta: {title: '素材链接', isTab: true}},
		{path: '/orderCenter',component: _import('orderCenter/orderCenter'),name: 'orderCenter',meta: {title: '订单中心',isTab: true}},
		{path: '/vueMchat',component: _import('vueMchat/vueMchat'),name: 'vueMchat',meta: {title: '聊天会话',isTab: true}},
		{path: '/memberDetails',component: _import('members/memberDetails'),name: 'memberDetails',meta: {title: '会员配置',isTab: true}},
		{path: '/vipPrivilege',component: _import('user/vipPrivilege'),name: 'vipPrivilege',meta: {title: '会员特权',isTab: true}},
		// {path: '/vipPrivilege', component: _import('vipPrivilege/vipPrivilege'), name: 'vipPrivilege', meta: { title: '会员特权',isTab: true} },
		{path: '/app', component: _import('app/app'), name: 'app', meta: { title: '升级配置', isTab: true } },
		{ path: '/chatRecord',component: _import('chatRecord/chatRecord'),name: 'chatRecord',meta: {title: '聊天记录',isTab: true}},
		{ path: '/universalMission',component: _import('universalMission/universalMission'),name: 'universalMission',meta: {title: '医院管理',isTab: true}},
		{path: '/locality', component: _import('locality/locality'), name: 'locality', meta: {title: '服务管理', isTab: true}},

		{ path: '/carBrandList',component: _import('carBrand/carBrandList'),name: 'carBrandList',meta: {title: '就诊人列表',isTab: true}},
		{ path: '/recruitList',component: _import('recruit/recruitList'),name: 'recruitList',meta: {title: '职务招商',isTab: true}},
		{ path: '/agent',component: _import('recruit/agent'),name: 'agent',meta: {title: '推广代理',isTab: true}},
		{ path: '/top',component: _import('recruit/top'),name: 'top',meta: {title: '排行榜管理',isTab: true}},
		//2022/12/6新增
		{ path: '/couponYhq', component: _import('campus/couponYhq'), name: 'couponYhq', meta: { title: '优惠券',isTab: true} },
		{ path: '/couponYhqList', component: _import('campus/couponYhqList'), name: 'couponYhqList', meta: { title: '优惠券列表',isTab: true} },
		{ path: '/couponuser', component: _import('campus/couponuser'), name: 'couponuser', meta: { title: '优惠券领取记录',isTab: true} },
		{path: '/IntegralGoods', component: _import('integral/IntegralGoods'), name: 'IntegralGoods', meta: {title: '充值分类', isTab: true}},
		{path: '/shifuScheduling',component: _import('riderScheduling/shifuScheduling'),name: 'shifuScheduling',meta: {title: '医院地图', isTab: true}},
		{path: '/riderScheduling',component: _import('riderScheduling/riderScheduling'),name: 'riderScheduling',meta: {title: '测试地图', isTab: true}},
		// 2023.04.17 4.8 版本 新增
		{path: '/masterPosition', component: _import('masterPosition/masterPosition'), name: 'masterPosition', meta: {title: '师傅位置记录', isTab: true}},
		{ path: '/comment', component: _import('comment/comment'), name: 'comment', meta: { title: '评价中心',isTab: true} },
		// 2023.05.16 6.0 版本 新增
		{path: '/creditScore', component: _import('integral/creditScore'), name: 'creditScore', meta: {title: '陪诊师等级', isTab: true}},
		{path: '/credit', component: _import('recruit/creditScore'), name: 'credit', meta: {title: '信用分明细', isTab: true}},

		//2025.10.22新增商城模块
		//商品系统
		{path: '/category', component: _import('modules/product/category'), name: 'category', meta: {title: '分类维护', isTab: true}},
		{path: '/brand', component: _import('modules/product/brand'), name: 'brand', meta: {title: '品牌管理', isTab: true}},

		{path: '/attrgroup', component: _import('modules/product/attrgroup'), name: 'attrgroup', meta: {title: '属性分组', isTab: true}},
		{path: '/baseattr', component: _import('modules/product/baseattr'), name: 'baseattr', meta: {title: '规格参数', isTab: true}},
		{path: '/saleattr', component: _import('modules/product/saleattr'), name: 'saleattr', meta: {title: '销售属性', isTab: true}},
		{path: '/attrupdate', component: _import('modules/product/attrupdate'), name: 'attrupdate', meta: {title: '达拉达', isTab: true}},

		{path: '/spu', component: _import('modules/product/spu'), name: 'spu', meta: {title: 'spu管理', isTab: true}},
		{path: '/spuadd', component: _import('modules/product/spuadd'), name: 'spuadd', meta: {title: '发布商品', isTab: true}},
		{path: '/manager', component: _import('modules/product/manager'), name: 'manager', meta: {title: '商品管理', isTab: true}},


		//优惠营销
		{path: '/coupon', component: _import('modules/coupon/coupon'), name: 'coupon', meta: {title: '优惠券管理', isTab: true}},
		{path: '/history', component: _import('modules/coupon/history'), name: 'history', meta: {title: '发放记录', isTab: true}},
		{path: '/subject', component: _import('modules/coupon/subject'), name: 'subject', meta: {title: '专题活动', isTab: true}},
		{path: '/seckill', component: _import('modules/coupon/seckill'), name: 'seckill', meta: {title: '秒杀活动', isTab: true}},
		{path: '/bounds', component: _import('modules/coupon/bounds'), name: 'bounds', meta: {title: '积分维护', isTab: true}},
		{path: '/full', component: _import('modules/coupon/full'), name: 'full', meta: {title: '满减折扣', isTab: true}},
		{path: '/memberprice', component: _import('modules/coupon/memberprice'), name: 'memberprice', meta: {title: '会员价格', isTab: true}},
		{path: '/seckillsession', component: _import('modules/coupon/seckillsession'), name: 'seckillsession', meta: {title: '每日秒杀', isTab: true}},


		//库存系统
		{path: '/wareinfo', component: _import('modules/ware/wareinfo'), name: 'wareinfo', meta: {title: '仓库维护', isTab: true}},
		{path: '/task', component: _import('modules/ware/task'), name: 'task', meta: {title: '库存工作单', isTab: true}},
		{path: '/sku', component: _import('modules/ware/sku'), name: 'sku', meta: {title: '商品库存', isTab: true}},


		{path: '/purchaseitem', component: _import('modules/ware/purchaseitem'), name: 'purchaseitem', meta: {title: '采购需求', isTab: true}},
		{path: '/purchase', component: _import('modules/ware/purchase'), name: 'purchase', meta: {title: '采购单', isTab: true}},


		//订单系统
		{path: '/order', component: _import('modules/order/order'), name: 'order', meta: {title: '订单查询', isTab: true}},
		{path: '/return', component: _import('modules/order/return'), name: 'return', meta: {title: '退货单处理', isTab: true}},
		{path: '/settings', component: _import('modules/order/settings'), name: 'settings', meta: {title: '等级规则', isTab: true}},
		{path: '/payment', component: _import('modules/order/payment'), name: 'payment', meta: {title: '支付流水查询', isTab: true}},
		{path: '/refund', component: _import('modules/order/refund'), name: 'refund', meta: {title: '退款流水查询', isTab: true}},


		


	],
	beforeEnter (to, from, next) {
		let token = Vue.cookie.get('token')
		if (!token || !/\S/.test(token)) {
			clearLoginInfo()
			next({name: 'login'})
		}
		next()
	}
}

const router = new Router({
	mode: 'history', //  hash
	scrollBehavior: () => ({y: 0}),
	isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
	routes: globalRoutes.concat(mainRoutes)
})

router.beforeEach((to, from, next) => {
	// 添加动态(菜单)路由
	// 1. 已经添加 or 全局路由, 直接访问
	// 2. 获取菜单列表, 添加并保存本地存储
	if (router.options.isAddDynamicMenuRoutes || fnCurrentRouteType(to, globalRoutes) === 'global') {
		next()
	} else {


		http({
			url: http.adornUrl('/sys/menu/nav'),
			method: 'get',
			params: http.adornParams()
		}).then(({data}) => {


			if (data && data.code === 0) {
				fnAddDynamicMenuRoutes(data.menuList)
				router.options.isAddDynamicMenuRoutes = true
				sessionStorage.setItem('menuList', JSON.stringify(data.menuList || '[]'))
				sessionStorage.setItem('permissions', JSON.stringify(data.permissions || '[]'))
				next({...to, replace: true})
			} else {
				sessionStorage.setItem('menuList', '[]')
				sessionStorage.setItem('permissions', '[]')
				next()
			}
		}).catch((e) => {
			console.log(`%c${e} 请求菜单列表和权限失败，跳转至登录页！！`, 'color:blue')
			router.push({name: 'login'})
		})
	}
})

/**
 * 判断当前路由类型, global: 全局路由, main: 主入口路由
 * @param {*} route 当前路由
 */
function fnCurrentRouteType (route, globalRoutes = []) {
	var temp = []
	for (var i = 0; i < globalRoutes.length; i++) {
		if (route.path === globalRoutes[i].path) {
			return 'global'
		} else if (globalRoutes[i].children && globalRoutes[i].children.length >= 1) {
			temp = temp.concat(globalRoutes[i].children)
		}
	}
	return temp.length >= 1 ? fnCurrentRouteType(route, temp) : 'main'
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes (menuList = [], routes = []) {
	var temp = []
	for (var i = 0; i < menuList.length; i++) {
		if (menuList[i].list && menuList[i].list.length >= 1) {
			temp = temp.concat(menuList[i].list)
		} else if (menuList[i].url && /\S/.test(menuList[i].url)) {
			menuList[i].url = menuList[i].url.replace(/^\//, '')
			var route = {
				path: menuList[i].url.replace('/', '-'),
				component: null,
				name: menuList[i].url.replace('/', '-'),
				meta: {
					menuId: menuList[i].menuId,
					title: menuList[i].name,
					isDynamic: true,
					isTab: true,
					iframeUrl: ''
				}
			}
			// url以http[s]://开头, 通过iframe展示
			if (isURL(menuList[i].url)) {
				route['path'] = `i-${menuList[i].menuId}`
				route['name'] = `i-${menuList[i].menuId}`
				route['meta']['iframeUrl'] = menuList[i].url
			} else {
				try {
					route['component'] = _import(`modules/${menuList[i].url}`) || null
				} catch (e) {
				}
			}
			routes.push(route)
		}
	}
	if (temp.length >= 1) {
		fnAddDynamicMenuRoutes(temp, routes)
	} else {
		mainRoutes.name = 'main-dynamic'
		mainRoutes.children = routes
		router.addRoutes([
			mainRoutes,
			{path: '*', redirect: {name: '404'}}
		])
		sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(mainRoutes.children || '[]'))
		console.log('\n')
		console.log('%c!<-------------------- 动态(菜单)路由 s -------------------->', 'color:blue')
		console.log(mainRoutes.children)
		console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->', 'color:blue')
	}
}

export default router
